package multithreading;

import java.util.Random;

public class Demo3_SailTicketsByThread {

    public static void main(String[] args) throws Exception {

        System.out.println("开始卖票");

        Thread bj = new Station("北京");
        Thread sh = new Station("上海");
        Thread hrb = new Station("哈尔滨");
        Thread nj = new Station("南京");

        bj.start();
        sh.start();
        hrb.start();
        nj.start();

        //保证优先执行当前线程，当前线程执行完毕后才执行主线程
        bj.join();
        sh.join();
        hrb.join();
        nj.join();

        System.out.println("票已售罄");

        System.out.println(Thread.currentThread().getId());
        System.out.println(Thread.currentThread().getName());
    }

}

/**
 * 自定义一个线程类，表示车站可以卖票
 */
class Station extends Thread{

    public static int ticketCount = 100;
    public String stationName = "";

    Random rand = new Random();


    public Station(String stationName){
        this.stationName = stationName;
    }

    @Override
    public void run() {
        try{
            while(true){
                //执行一次，票就被卖了一张
                ticketCount--;
                System.out.println(this.stationName+"卖了一张车票，剩余："+ticketCount+"张火车票");

                Thread.sleep(rand.nextInt(500));

                //如果票已卖完，则退出循环
                if(ticketCount<=0){
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
